/**
 * 定位服务封装
 * 封装微信小程序定位API，提供高精度定位服务
 */

/**
 * 获取当前位置（单次）
 * @param {Object} options - 配置选项
 * @param {String} options.type - 坐标类型 'gcj02' | 'wgs84'，默认'gcj02'
 * @param {Boolean} options.isHighAccuracy - 是否高精度，默认true
 * @returns {Promise} 位置信息
 */
function getCurrentLocation(options = {}) {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: options.type || 'gcj02',
      isHighAccuracy: options.isHighAccuracy !== false,
      success: (res) => {
        resolve({
          latitude: res.latitude,
          longitude: res.longitude,
          speed: res.speed || 0,
          accuracy: res.accuracy || 0,
          altitude: res.altitude || 0,
          timestamp: Date.now()
        });
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 检查定位权限
 * @returns {Promise<Boolean>} 是否已授权
 */
function checkLocationAuth() {
  return new Promise((resolve) => {
    wx.getSetting({
      success: (res) => {
        const authStatus = res.authSetting['scope.userLocation'];
        resolve(authStatus === true);
      },
      fail: () => {
        resolve(false);
      }
    });
  });
}

/**
 * 请求定位权限
 * @returns {Promise<Boolean>} 是否授权成功
 */
function requestLocationAuth() {
  return new Promise((resolve) => {
    wx.authorize({
      scope: 'scope.userLocation',
      success: () => {
        resolve(true);
      },
      fail: () => {
        // 用户拒绝授权，引导到设置页
        wx.showModal({
          title: '需要定位权限',
          content: '为了提供地图定位和导航功能，需要获取您的位置信息',
          confirmText: '去设置',
          success: (res) => {
            if (res.confirm) {
              wx.openSetting();
            }
            resolve(false);
          }
        });
      }
    });
  });
}

/**
 * 持续定位管理类
 */
class ContinuousLocation {
  constructor(options = {}) {
    this.interval = options.interval || 2000; // 定位间隔，默认2秒
    this.onUpdate = options.onUpdate || (() => {}); // 位置更新回调
    this.onError = options.onError || (() => {}); // 错误回调
    this.timer = null;
    this.isRunning = false;
  }

  /**
   * 开始持续定位
   */
  start() {
    if (this.isRunning) return;
    
    this.isRunning = true;
    this._updateLocation(); // 立即执行一次
    
    this.timer = setInterval(() => {
      this._updateLocation();
    }, this.interval);
  }

  /**
   * 停止持续定位
   */
  stop() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    this.isRunning = false;
  }

  /**
   * 内部方法：更新位置
   */
  async _updateLocation() {
    try {
      const location = await getCurrentLocation();
      this.onUpdate(location);
    } catch (err) {
      this.onError(err);
    }
  }
}

module.exports = {
  getCurrentLocation,
  checkLocationAuth,
  requestLocationAuth,
  ContinuousLocation
};

